package listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import config.Config;
import config.SocketConfig;

import service.SunVoteServer;
import ui.ClassIpUI;
import ui.LoginUI;
import util.Java_JDBC;
import util.SQLStart;

/**
 * 实现接口ActionListener
 * @author wj
 *
 */
public class LoginListener implements ActionListener{
	private JTextField jl_user;
	private JPasswordField jl_pass;
	private LoginUI loginUI;
	private JButton jb1, jb2;
	public LoginListener(LoginUI loginUI) {
		this.loginUI = loginUI;
		this.jl_user = loginUI.jTextField;
		this.jl_pass = loginUI.jPasswordField;
		this.jb1 = loginUI.jb1;
		this.jb2 = loginUI.jb2;
	}
	
	/**
	 * 对输入的信息进行判断
	 * 输出结果
	 */
	public void actionPerformed(ActionEvent e){
		if(e.getSource() == jb1) {
			Thread thread  = new Thread(new myRunnable());
			thread.start();
		}else if(e.getSource() == jb2){
			loginUI.dispose();
			System.exit(0); 
		}
	}
	
	class myRunnable implements Runnable {

		@Override
		public void run() {
			try {
				if(!SQLStart.netStart()) {
					JOptionPane.showMessageDialog(loginUI, "错误，开启服务器失败");
					return;
				}
				Config.sqlSate = new Java_JDBC().teacherLogin(jl_user.getText(), new String(jl_pass.getPassword()));
				try {
					if(Config.sqlSate == 41){
						if(SocketConfig.ipAddress==null) {
							InetAddress ip = InetAddress.getLocalHost();
							SocketConfig.ipAddress = ip.getHostAddress();
							new Thread(new SunVoteServer()).start();
						}
						new ClassIpUI().setVisible(true);
						loginUI.dispose();
					}
					else if(Config.sqlSate == 40){
						JOptionPane.showMessageDialog(loginUI, "提示：请检查用户名，密码是否正确");  
					}else {
						JOptionPane.showMessageDialog(loginUI, "错误：请开启数据库服务");  
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			} catch (Exception e2) {
				JOptionPane.showMessageDialog(loginUI, "请检查数据库是否开启"); 
			}
		}
	}
}
